// Copyright (C) 2020 Focus Media Holding Ltd. All Rights Reserved.

package cn.pacerx.running.db.typehandler;

import java.util.Collection;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;

import com.google.common.base.Joiner;

/**
 * TypeHandler for String collection
 *
 * @param <C> collection type
 */
public abstract class StringCollectionTypeHandler<C extends Collection<?>> extends StringAdaptorTypeHandler<C> {
    private static final String SEPARATOR = ",";

    @Override
    protected final String toString(C parameter) {
        return Joiner.on(SEPARATOR).join(parameter);
    }

    @Override
    protected final C fromString(String s) {
        if (StringUtils.isBlank(s)) {
            return toCollection(new String[0]);
        }
        return toCollection(Stream.of(s.split(SEPARATOR)).map(StringUtils::trim).toArray(String[]::new));
    }

    protected abstract C toCollection(String[] strings);
}
